#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;
void Create_a_txt(const char * file1)
{
        ofstream out_file(file1,ios::out);
        if(!out_file)
        {
                cout<<"file error"<<endl;
                return;
        }
        out_file<<"how are you today?"<<endl;
        out_file<<"i'm fine thank you and you?"<<endl;
        out_file<<"i'm not so fine"<<endl;
        out_file<<"i think you need to have a rest"<<endl;
        out_file<<"thank you"<<endl;
        out_file.close();
        return;
}
void print_a_txt(const char *file)
{
        ifstream out_file(file);
        string temp;
        while(getline(out_file,temp))
        {
                cout<<temp<<endl;
        }
        out_file.close();
}
void scan_file(const char *filename, map<string, int> &ans)
{
    ifstream in_file(filename);
    if (!in_file)
    {
        cout << "file error" << endl;
        return;
    }
    string word;

    while ( in_file >> word)
    {
        if (ans.count(word) == 0)
            ans[word] = 1;
        else
            ans[word]++;
    }
}
int main()
{
    const char *file = "file_4.txt";
    const char *str = "you";
    Create_a_txt(file);
    print_a_txt(file);

    map<string, int> ans;
    scan_file(file, ans);
    vector<pair<string, int>> v;
    for (auto a : ans)
        v.push_back(a);
    sort(v.begin(), v.end(), [](const pair<string,int>& a,const pair<string,int>&  b)
         {
             if(a.second>b.second)
	     {
                 return true;
             }
             else if(a.second < b.second)
	     {
                 return false;
             }
             else
                return a.first<b.first;
         });
    ofstream out_file("ans.txt",ios::out);
    if(!out_file)
    {
        cout<<"error file";
        return -1;
    }
    for(auto a:v)
    {
        cout << a.first << ":" << a.second << endl;
        out_file<< a.first << ":" << a.second << endl;
    }
    out_file.close();
    return 0;
}
